package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//获取完整文件名 jzy.jpg
            String ext = filename.substring(filename.lastIndexOf(".") + 1);//获取后缀  substring含头不含尾

            byte[] bytes = file.getBytes();
            String path = FastdfsUtil.upload(bytes, ext);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){
        try {
            String pathTmp = path.substring(1);//   group1/M00/03/67/CgAIC2O32fOAFI83AADCnuiozE8863.jpg  去掉第一个斜杠
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));//  group1   从0截取到第一个斜杠之前,拿到groupName
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);//M00/03/67/CgAIC2O32fOAFI83AADCnuiozE8863.jpg

            System.out.println(groupName);
            System.out.println(remotePath);
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败!"+e.getMessage());
        }

    }
}
